const mongoose = require("mongoose");

class Db {
	constructor(model) {
		this.model = model;
	}
	_connect(){
		// 如果已经连接上了,返回一个成功的Promise实例
		if(mongoose.connection.readyState === 1) return Promise.resolve();
		return mongoose.connect("mongodb://127.0.0.1:27017/hy01",{
			serverSelectionTimeoutMs:1000
		})
	}
	// 插入一条文档
	async insertOne(obj){
		await this._connect();// 连接数据库
		return this.model(obj).save();
	}
	// 根据条件返回文档的条数
	async count(obj){
		await this._connect();
		return this.model.countDocuments(obj);
	}
	// whereObj:搜索条件
	// sortObj:排序
	// limit:获取的条数
	// skip:跳过的条数
	async find({whereObj={},sortObj={},limit=0,skip=0}){
		console.log(whereObj,sortObj,limit,skip)
		await this._connect();
		return this.model.find(whereObj).sort(sortObj).limit(limit).skip(skip);
	}
	// 根据条件获取一条数据
	async findOne(whereObj={}){
		await this._connect();
		return this.model.findOne(whereObj);
	}
	async deleteOneById(_id){
		await this._connect();
		return this.model.deleteOne({_id});
	}
	// _id:修改的条件
	// upObj:更改的内容
	async updateOneById(_id,upObj){
		await this._connect();
		return this.model.updateOne({_id},upObj);
	}
}
module.exports = Db;